<template>
  <basic-dialog :visible="show"
                :title="`${forCreate? '添加设备': '编辑设备'}`"
                :min-width="'700px'"
  >
    <!-- 正文 -->
    <q-form @submit="submit" @reset="reset" greedy>
      <div class="margin-t-20 margin-b-20 padding-l-20 padding-r-20 scrollbar overflow-auto" style="max-height: 560px">
        <div class="row dialog-content" style="padding: 0">
          <div class="col">
            <yz-input
              :rules="[0, 16]"
              :is-disable="forEdit"
              v-model.trim="form.assetNumber"
              :maxlength="64"
              :hintRule="[ val => /^[\da-zA-Z\-]+$/.test(val) || `只能输入数字,字母和字符-`]"
              title="设备编号"
            />
            <yz-input
              :rules="[0]"
              v-model.trim="form.deviceName"
              :maxlength="20"
              title="设备名称"
            />
            <yz-input
              v-model="form.equipmentType"
              inputType="select"
              :options="equipmentTypeOption"
              :rules="[0]"
              isRule
              :hint-rule="[
                val => (val !==null && val !== undefined) || ' 请选择设备类型'
              ]"
              title="设备类型"
            />
            <yz-input
              v-model.trim="form.model"
              :maxlength="20"
              title="设备型号"
            />
            <yz-input
              v-model.trim="form.ncSystem"
              :maxlength="20"
              title="数控系统"
            />
            <yz-input
              v-model.trim="form.deviceSpec"
              :maxlength="20"
              title="设备规格"
            />
            <yz-input
              v-model="form.toolBankNumber"
              inputType="select"
              :options="toolBankNumberOption"
              :rules="[0]"
              title="刀库位数"
            />
            <select-tree label="所在位置" :sel-tree="form.location" :disable="forView" is-require
                         :tree-list="locationOption" node-key="hash" @treeChange="_changeTreeNode"/>

            <yz-input
              v-model.trim="form.manufacturer"
              :maxlength="20"
              title="设备厂家"
            />
            <yz-input
              v-model.trim="form.thirdId"
              :maxlength="64"
              :hint-rule="[val => !/^\s+$/.test(val) || '不能全为空格符']"
              tips="关联ID用于设备数据推送关联客户设备, 如有推送业务必须填写否则无法推送成功"
              title="关联ID"
            />
          </div>

          <div class="col" style="padding-left: 10px">
            <!-- 照片 -->
            <div class="photo-box">
              <q-img
                class="photo"
                :src="form.photoUrls"
                spinner-color="white"
              >
                <div
                  v-if="!form.photoUrls"
                  style="height: 100%; width: 100%; background: #d0d6fb;"
                />
                <q-btn
                  class="upload-btn"
                  unelevated
                  @click="_onUploadPhotoClick"
                  :disable="forView"
                  :class="{ 'dashed-border': !form.photoUrls }"
                >
                  <q-icon
                    v-if="!form.photoUrls"
                    size="96px"
                    class="photo"
                    name="iconfont icontubiao-56"
                    style="font-size: 96px !important;"
                    color="white"
                  />
                </q-btn>
              </q-img>
              <input
                ref="fileInput"
                type="file"
                style="display: none;"
                accept="image/jpeg, image/png"
                @input="onPhotoFileSelected"
              />
            </div>
            <yz-input
              v-model="form.cutterGrooveNum"
              inputType="select"
              :options="cutterGrooveNumOption"
              :rules="[0]"
              tips="一个刀位可装的刀具数量。"
              title="刀槽数"
            />
            <yz-input
              v-model="form.station"
              inputType="select"
              :options="stationOption"
              :rules="[0]"
              isRule
              :hint-rule="[
                val => (val !==null && val !== undefined) || ' 请选择工位'
              ]"
              title="工位"
            />
            <yz-input inputType="date"
                      title="进厂日期"
                      class="date margin-b-20"
                      clearable
                      :isRange="false"
                      :disabledType="notAfterToday"
                      v-model="form.incomingDate"/>
            <yz-input
              v-model="form.status"
              inputType="select"
              :options="statusOption"
              title="启用状态"
            />
          </div>
        </div>
        <div class="row">
          <div class="upload-header">
            <span class="font-14 text-weight-bold">设备档案</span>
            <div style="float: right; display: inline-block">
              <q-btn
                :disable="forView"
                flat round dense
                icon="iconfont icontubiao-50"
                style="min-height: auto; min-width: auto;"
                @click="_onUploadDocumentClick"
              >
                <input
                  ref="documentInput"
                  type="file"
                  style="display: none;"
                  accept="image/jpeg, image/png, application/pdf"
                  @input="onDocumentFileSelected"
                />
              </q-btn>
              <q-btn
                :disable="forView || form.documentUrls.filter(o => o.checked).length === 0"
                flat round dense
                icon="iconfont icontubiao-16"
                @click="deleteDocumentFile"
              >
              </q-btn>
            </div>
          </div>
          <q-scroll-area class="box-content bg-white bordered" :thumb-style="thumbStyle" style="width:100%; height: 78px;padding: 10px 10px; border: 1px solid #d3d3d3">
            <div class="sudoku_row"  >
              <div class="sudoku_item " v-for="(document,index) in form.documentUrls" :key="index">
                <div @click="showFile(judgeFileExtension(document.name).type, document)" v-ripple class="file_item relative-position">
                  <div style="display: flex">
                    <q-checkbox :disable="forView" v-model="document.checked" />
                    <!--<i class="iconfont" :class="[judgeFileExtension(processFile.name).icon]" :style="{color: judgeFileExtension(processFile.name).color}"/>-->
                    <span class="text-ellipsis" style="width: 100px; display: inline-block;line-height: 40px;margin-left: 3px">
                          {{ document.name }}
                          <q-tooltip>{{ document.name }}</q-tooltip>
                        </span>
                  </div>
                </div>
              </div>
            </div>
          </q-scroll-area>
        </div>
      </div>
      <!-- 底部按钮 -->
      <q-separator/>
      <div class="dialog-footer text-center footer">
        <q-btn class="q-mr-md" outline color="primary" @click="$emit('close')" style="width: 96px; min-height: 32px; font-size: 16px; padding: 0px">
          取消
        </q-btn>
        <q-btn
          :disable="forView"
          style="width: 96px; min-height: 32px; font-size: 16px; padding: 0px"
          label="确定"
          color="primary"
          unelevated
          type="submit"
          :loading="submitting"
        />
      </div>
    </q-form>
    <!--查看pdf-->
    <look-pdf ref="showPdf"/>
    <!--查看图片-->
    <look-img ref="showImg"/>
  </basic-dialog>
</template>

<script>
import SelectTree from 'src/components/select-tree'
import { getStation } from 'src/boot/tpm/equipment-record'
import lookImg from 'src/components/look-img'
import lookPdf from 'src/components/look-pdf'
import { mapGetters } from 'vuex'
import { uploadFlie } from '../../../boot/template/template-upload'
import moment from 'moment'
import _ from 'lodash'
export default {
  name: 'record-detail',
  props: {
    forView: {
      type: Boolean,
      default: false
    },

    forEdit: {
      type: Boolean,
      default: false
    },

    forCreate: {
      type: Boolean,
      default: false
    },

    show: {
      type: Boolean,
      default: false,
      required: true
    },

    equipmentTypeOptions: {
      type: Array
    },

    locationOptions: {
      type: Array
    }
  },
  components: {
    SelectTree,
    lookImg,
    lookPdf
  },
  computed: {
    ...mapGetters([
      'client'
    ]),
    toolBankNumberOption () {
      const member = _.range(1, 100)
      return member.map(v => {
        return {
          label: v,
          value: v
        }
      })
    }
  },
  data () {
    return {
      thumbStyle: this.CommonConfig.thumbStyle, // 滚动条样式
      submitting: false, // 提交表单
      form: {
        id: '', // 编辑id
        stationId: '', // 编辑时工位id的替代字段，因为编辑是拿不到所在位置信息
        documentUrls: [], // 附件地址
        photoUrls: '', // 图片地址
        assetNumber: '', // 设备编号
        deviceName: '', // 设备名称
        equipmentType: null, // 设备类型
        status: 1, // 启用状态
        model: '', // 设备型号
        cutterGrooveNum: 1, // 刀位槽数
        deviceSpec: '', // 设备规格
        toolBankNumber: 1, // 刀库位数
        ncSystem: '', // 数控系统
        location: {
          id: null,
          level: null,
          label: '',
          hash: ''
        }, // 所在位置
        station: '', // 所在工位
        manufacturer: '', // 设备厂家
        incomingDate: '', // 进厂日期
        thirdId: '' // 关联id
      },
      fileName: null, // 文件名（用于订阅）
      locationOption: [], // 所在位置数据源
      equipmentTypeOption: [], // 设备类型数据源
      stationOption: [], // 所在工位数据源
      currentFileName: null, // 当前上传文件名
      statusOption: [{
        value: 1,
        label: '启用'
      }, {
        value: 0,
        label: '禁用'
      }], // 启用状态
      cutterGrooveNumOption: [
        {
          label: 1,
          value: 1
        },
        {
          label: 2,
          value: 2
        },
        {
          label: 3,
          value: 3
        },
        {
          label: 4,
          value: 4
        },
        {
          label: 5,
          value: 5
        }
      ]
    }
  },
  methods: {
    // 非昨日之前
    notAfterToday (date) {
      const today = moment(new Date()).startOf('day')
      return date > new Date(today)
    },
    // 校验时间有效性
    judgeDate (val) {
      if (!val) {
        return true
      }
      const dataOld = `${val}T00:00:00`
      const dateNew = new Date(dataOld)
      const dateNow = new Date()
      return dateNow > dateNew
    },

    // 检查prop
    _checkProps: function () {
      // forView、forEdit、forCreate 均为 false 或多于一项为 true
      let trueCount = [this.forView, this.forEdit, this.forCreate].filter(o => o).length
      if (trueCount !== 1) {
        throw new Error('for-view、for-code-edit、for-create 三者必须有且只有一项为 true')
      }
    },

    // 选择组织机构树节点 *
    _changeTreeNode: function (val) {
      this.stationOption = []
      this.form.station = null
      if (val.id && val.label && val.hash) {
        this.form.location.id = val.id
        this.form.location.level = val.level
        this.form.location.label = val.label
        this.form.location.hash = val.hash
        this.stationOption = []
        getStation(val.level, val.id).then(res => {
          for (const i of res.data.list) {
            if (res.data.list.length !== 0) {
              this.stationOption.push({
                value: i['id'],
                label: i['opdesc']
              })
            }
          }
        })
      } else {
        this.stationOption = []
        this.form.station = ''
        this.form.location = {
          id: null,
          level: null,
          label: '',
          hash: ''
        }
      }
    },

    // 上传照片
    _onUploadPhotoClick: function () {
      // 触发文件选择
      this.$refs.fileInput.dispatchEvent(new MouseEvent('click'))
    },

    _onUploadDocumentClick () {
      this.$refs.documentInput.dispatchEvent(new MouseEvent('click'))
    },

    // 选择照片
    onPhotoFileSelected () {
      if (!this.$utils.fileTypeHoldUp(this.$refs.fileInput.files[0].name, ['.jpg', '.jpeg', '.png'])) {
        return
      }
      let file = this.$refs.fileInput.files
      let fileSize = file[0].size
      let fileMaxSize = 1024 * 1024 * 5
      if (fileSize <= fileMaxSize) {
        const path = this.CommonConfig.ossFilePath.deviceImagesDir
        let res = this.$getUploadPath(file, path)
        this.fileName = res.fileNameNew
        this.onSubscribe('img')
        this.uploadFlie(res.uploadPath, file[0], res.fileNameNew)
        // let url = [res.data]
        // url.push(res.requestUrls[0].replace(/\?acl.+$/g, ''))
      } else {
        this.$q.dialog({
          title: `<p class="dialog-notice-title">
      <i class="iconfont icontubiao-53" ></i> 文件大小不能超过5M</p>`,
          html: true,
          ok: {
            unelevated: true,
            label: '确认'
          }
        })
      }
      this.$refs.fileInput.value = null
    },

    // 上传设备档案
    onDocumentFileSelected () {
      if (!this.$utils.fileTypeHoldUp(this.$refs.documentInput.files[0].name, ['.jpg', '.jpeg', '.png', '.pdf'])) {
        return
      }
      let file = this.$refs.documentInput.files
      this.currentFileName = file[0].name
      let fileSize = file[0].size
      let fileMaxSize = 1024 * 1024 * 20
      if (fileSize <= fileMaxSize) {
        const path = this.CommonConfig.ossFilePath.documentDir
        let res = this.$getUploadPath(file, path)
        this.fileName = res.fileNameNew
        this.onSubscribe('file')
        this.uploadFlie(res.uploadPath, file[0], res.fileNameNew)
      } else {
        this.$q.dialog({
          title: `<p class="dialog-notice-title">
      <i class="iconfont icontubiao-53" ></i> 文件大小不能超过20M</p>`,
          html: true,
          ok: {
            unelevated: true,
            label: '确认'
          }
        })
      }
      this.$refs.documentInput.value = null
    },
    // 上传文件
    uploadFlie (uploadPath, files, fileNameNew) {
      uploadFlie(uploadPath, files, fileNameNew).then(res => {
        if (res.code !== '1200') {
          this.$showErrTips('上传失败，请稍后重试')
          this.closeUbscribeTopic()
        }
      }).catch(res => {
        console.log(res)
        this.$refs.documentInput.value = null
        this.closeUbscribeTopic()
      })
    },
    onSubscribe (type) {
      if (this.client) {
        if (type === 'img') {
          this.client.subscribe(
            `${this.CommonConfig.socketConfig.SOCKET_TOPIC.uploadFile.subscribeTopic}${this.fileName}`, this.onImgMessageArrived, { id: `${this.fileName}` }
          )
        } else {
          this.client.subscribe(
            `${this.CommonConfig.socketConfig.SOCKET_TOPIC.uploadFile.subscribeTopic}${this.fileName}`, this.onFileMessageArrived, { id: `${this.fileName}` }
          )
        }
      } else {
        setTimeout(() => {
          this.onSubscribe()
        }, 200)
      }
    },
    onImgMessageArrived (message) {
      let msg = JSON.parse(message.body).data
      if (msg.requestId !== this.fileName) {
        return
      }
      if (msg.code + '' !== '200') {
        this.$showErrTips('上传失败，请稍后重试')
        this.closeUbscribeTopic()
        return
      }
      this.form.photoUrls = msg.data
      this.closeUbscribeTopic()
    },
    onFileMessageArrived (message) {
      let msg = JSON.parse(message.body).data
      if (msg.requestId !== this.fileName) {
        return
      }
      if (msg.code + '' !== '200') {
        this.$showErrTips('上传失败，请稍后重试')
        this.closeUbscribeTopic()
        return
      }
      let url = this.form.documentUrls
      url.push({
        url: msg.data,
        name: this.currentFileName,
        checked: false
      })
      this.form.documentUrls = url
      this.currentFileName = null
      this.closeUbscribeTopic()
    },
    closeUbscribeTopic () {
      this.client.unsubscribe(`${this.fileName}`)
      this.$q.loading.hide()
    },
    // 预览文件
    showFile (type, item) {
      if (type === 'pdf') {
        this.$refs.showPdf.showDialog(item.url)
      } else {
        this.$refs.showImg.showDialog(item.url)
      }
    },

    // 判断文件后缀
    judgeFileExtension (name) {
      let index = name.lastIndexOf('.')
      let ext = name.substr(index + 1)
      if (ext.toLowerCase() === 'pdf') {
        return {
          icon: 'icontubiao-54',
          color: 'red',
          type: 'pdf'
        }
      } else {
        return {
          icon: 'icontubiao-56',
          color: '#5f77fd',
          type: 'img'
        }
      }
    },

    // FIXME ME 以下代码只删除了数据库索引，有空时应重构将oss文件一并删除
    deleteDocumentFile () {
      if (this.form.documentUrls.length <= 0) {
        return
      }
      let newArr = this.form.documentUrls.filter(o => o.checked === false)
      this.form.documentUrls = Object.assign(newArr)
    },

    // 提交表单
    submit () {
      this.$emit('submit', this.forView, this.forCreate, this.forEdit, this.form)
    },

    // 重置表单
    reset () {
      this.form.documentUrls = [] // 附件地址
      this.form.photoUrls = '' // 图片地址
      this.form.assetNumber = '' // 设备编号
      this.form.deviceName = '' // 设备名称
      this.form.equipmentType = null // 设备类型
      this.form.status = 1 // 启用状态
      this.form.model = null // 设备型号
      this.form.deviceSpec = '' // 设备规格
      this.form.toolBankNumber = 1 // 刀库位数
      this.form.cutterGrooveNum = 1 // 刀位槽数
      this.form.ncSystem = '' // 数控系统
      this.form.station = '' // 所在工位
      this.form.manufacturer = '' // 设备厂家
      this.form.incomingDate = '' // 进厂日期
      this.form.thirdId = '' // 进厂日期
      this.stationOption = []
      this.form.location = {
        id: null,
        level: null,
        label: '',
        hash: ''
      } // 所在位置
    },

    // 平坦化的部门
    flattenedLocationOption: function () {
      let flatArr = []

      // 递归平坦化每一级节点
      this.locationOption.forEach(flattenNode)

      function flattenNode (node) {
        flatArr.push(Object.assign({}, node, { children: undefined }))

        if (node.children instanceof Array) {
          node.children.forEach(flattenNode)
        }
      }

      return flatArr
    },

    // 查找节点
    filterNode (val) {
      for (let i of this.flattenedLocationOption()) {
        if (i['id'] === val.schemeId && i['level'] === val.schemeLevel) {
          return i.label
        }
      }
    },

    // 编辑填充表单
    assignment (val) {
      this.form.id = val.id
      this.form.documentUrls = val.documents.length === 0 ? [] : val.documents // 附件地址
      this.form.documentUrls = this.form.documentUrls.map(o => {
        return {
          url: o.url,
          name: o.name,
          checked: false
        }
      })
      this.form.photoUrls = val.photoUrls.length === 0 ? '' : val.photoUrls[0] // 图片地址
      this.form.assetNumber = val.assetNumber // 设备编号
      this.form.deviceName = val.name // 设备名称
      // this.form.equipmentType = val.ncType // 设备类型
      this.form.status = val.statusCode // 启用状态
      this.form.model = val.model // 设备型号
      this.form.deviceSpec = val.deviceSpec // 设备规格
      this.form.equipmentType = val.typeCode // 设备类型
      this.form.toolBankNumber = val.toolMagazineCapacity // 刀库位数
      this.form.cutterGrooveNum = val.cutterGrooveNum // 刀库位数
      this.form.ncSystem = val.ncType // 数控系统
      this.form.manufacturer = val.producer // 设备厂家
      this.form.incomingDate = val.introduceDate // 进厂日期
      this.form.thirdId = val.thirdId // 进厂日期
      this.form.location = {
        id: val.schemeId,
        level: val.schemeLevel,
        label: this.filterNode(val),
        hash: `${val.schemeLevel}:${val.schemeId}`
      } // 所在位置
      this.stationOption = []
      this.form.station = null
      val.schemeId && getStation(val.schemeLevel, val.schemeId).then(res => {
        if (res.data.list.length !== 0) {
          for (const i of res.data.list) {
            this.stationOption.push({
              value: i['id'],
              label: i['opdesc']
            })
          }
          this.form.station = val.workCenterId
        } else {
          this.stationOption = []
          this.form.station = null
        }
      })
    }
  },
  watch: {
    equipmentTypeOptions (val) {
      const arr = val.filter(opt => opt.enableFlag)
      this.equipmentTypeOption = arr
    },
    locationOptions (val) {
      this.locationOption = val
    }
  },
  created () {
    this._checkProps()
  }
}
</script>

<style scoped lang="stylus">
>>>.mx-datepicker{
  width 233px !important
}
  .field {
    /deep/ .q-field__messages {
      margin-left 96px
    }
  }
  /deep/ .q-select__dropdown-icon {
    width 24px
    height 24px
    font-size 24px
    color rgba(0, 0, 0, .54)
  }
  /deep/ .q-img__content {
    display flex
    justify-content center
    align-items center
  }
  .upload-header {
    width 100%
    height 40px
    background $primary
    padding 0 10px
    line-height 40px
    border-top-left-radius:6px;
    border-top-right-radius:6px;
    border-bottom-right-radius:0;
    border-bottom-left-radius:0;
    color: white
  }
  .upload-body {
    width 100%
    height 78px
    border 1px solid #999
    overflow-y hidden
  }
  .label-width {
    width 75px
  }
  .card {
    min-width 712px
  }
  .footer {
    padding:10px 10px
  }
  .photo-box {
    margin-bottom 20px
    display flex
    flex-direction column
    align-items center
    height 292px
    justify-content space-between

    .photo {
      height 280px
      width 280px
      border 1px solid #D3D3D3
      border-radius 6px

      .upload-btn {
        height 100%
        width 100%

        &.dashed-border:after {
          $border-padding = 28px

          content ""
          display block
          position absolute
          top 0
          left 0
          height "calc(100% - %s)" % $border-padding
          width "calc(100% - %s)" % $border-padding
          margin ($border-padding / 2)
          border 1px dashed #FFF
        }
      }
    }
  }
  .sudoku_row{
    display: flex;
    align-items: center;
    width:100%;
    flex-wrap: wrap;
  }
  .sudoku_item{
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    width:25%;
    padding: 3px
  }
  .file_item{
    display flex
    justify-content center
    align-items center
    width 100%
    height 40px
    border-radius 6px
    cursor pointer
    border 1px solid #d3d3d3
    /*    background: #f7b82d
        color: #fff*/
    box-shadow: 0px 1px 5px 0px rgba(0,0,0,0.15)
  }
  .date{
    >>>.form-name{
      width 88px
      display inline-block
    }
  }
  >>>.name{
    font-size 16px !important
  }
  >>>.q-btn{
    .q-icon{
      font-size 18px !important
    }
  }
  .photo{
    .q-icon{
      font-size 96px !important
    }
  }
</style>
